<!-- 普通发货 -->
<template>
  <div>
    <el-form :inline="true" ref="form" :model="form" :rules="rules" label-width="180px">

      <el-divider content-position="left"><span class="divider_color">装卸货信息</span></el-divider>
      <el-row type="flex" align="middle">
        <el-col :span="9">
          <el-row>
            <el-col :span="20">
              <el-form-item label="装货地址" prop="placeOfLoading">
                <el-input class="o_input" v-model="form.placeOfLoading" suffix-icon="el-icon-location-information" placeholder="点击选择装货地址" @focus="openMapF = true" />
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-button type="success" plain @click="openOrderAddressF = true">常用地址</el-button>
            </el-col>
          </el-row>
          <el-row>
            <el-col>
              <el-form-item label="发货方" prop="consignor">
                <el-input class="o_input" v-model.trim="form.consignor" placeholder="请输入发货方名称" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col>
              <el-form-item label="发货方证件" prop="consignorId">
                <el-input class="o_input" v-model.trim="form.consignorId" placeholder="请输入发货方统一社会信用代码或个人证件号" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col>
              <el-form-item label="装货联系电话" prop="loadLinkTel">
                <el-input class="o_input" v-model="form.loadLinkTel" placeholder="请输入装货联系电话" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-col>
        <el-col :span="4" :push="1">
          <img style="width: 60px; height: 60px;" src="@/assets/images/img06.png" fit="fit"></img>
        </el-col>
        <el-col :span="9">
          <el-row>
            <el-col :span="20">
              <el-form-item label="收货地址" prop="goodsReceiptPlace">
                <el-input class="o_input" v-model="form.goodsReceiptPlace" suffix-icon="el-icon-location-information" placeholder="点击选择收货地址" @focus="openMapS = true" />
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-button type="success" plain @click="openOrderAddressSFuc">常用地址</el-button>
            </el-col>
          </el-row>
          <el-row>
            <el-col>
              <el-form-item label="收货方" prop="consignee">
                <el-input class="o_input" v-model.trim="form.consignee" placeholder="请输入收货方名称" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col>
              <el-form-item label="收货方证件" prop="consigneeId">
                <el-input class="o_input" v-model.trim="form.consigneeId" placeholder="请输入收货方统一社会信用代码或个人证件号" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col>
              <el-form-item label="卸货联系电话" prop="receiptLinkTel">
                <el-input class="o_input" v-model="form.receiptLinkTel" placeholder="请输入卸货联系电话" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-col>
        <el-col :span="2"></el-col>
      </el-row>

      <el-divider content-position="left"><span class="divider_color">货物信息</span></el-divider>
      <el-row>
        <el-col>
          <el-form-item label="运费金额(元/车)" prop="totalMonetaryAmount">
            <el-input-number v-model="form.totalMonetaryAmount" controls-position="right" :precision="2" :min="0" :step="1"></el-input-number>
          </el-form-item>
          <el-form-item label="预计发货时间" prop="leaveTime">
            <el-date-picker clearable
              v-model="form.leaveTime"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="选择预计发货时间">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="用车需求" prop="carNeed">
            <el-input class="o_input" v-model="form.carNeed" placeholder="请输入用车需求" maxlength="30" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col>
          <el-form-item label="备注" prop="remark">
            <el-input style="width: 318%;" v-model="form.remark" type="textarea" maxlength="200" autosize placeholder="请输入备注" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-for="(goods, index) in form.orderGoods" :key="index">
        <el-col>
          <el-form-item
            label="货物名称"
            :prop="'orderGoods.' + index + '.descriptionOfGoods'"
            :rules="{ required: true, message: '货物名称不能为空', trigger: 'blur' }">
            <el-input v-model="goods.descriptionOfGoods" placeholder="请输入货物名称" />
          </el-form-item>
          <el-form-item
            label="货物类型"
            :prop="'orderGoods.' + index + '.cargoTypeClassificationCode'"
            :rules="{ required: true, message: '货物类型不能为空', trigger: ['blur', 'change'] }">
            <el-select v-model="goods.cargoTypeClassificationCode" placeholder="请选择货物类型">
              <el-option
                v-for="item in cargoTypeClassificationOptions"
                :key="item.dictValue"
                :label="item.dictLabel"
                :value="item.dictValue">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="货物毛重(千克)"
            :prop="'orderGoods.' + index + '.goodsItemGrossWeight'"
            :rules="{ validator: weightRules, trigger: ['blur', 'change'] }">
            <el-input-number v-model="goods.goodsItemGrossWeight" controls-position="right" :precision="3" :min="0" :step="1"></el-input-number>
          </el-form-item>&nbsp;&nbsp;
          <el-button v-if="index == 0 && form.orderGoods.length < 10" type="success" plain @click="addDomain">添加</el-button>
          <el-button v-else type="danger" plain @click.prevent="removeDomain(goods)">删除</el-button>
        </el-col>
      </el-row>

      <el-divider content-position="left"><span class="divider_color">承运信息</span></el-divider>
      <el-row type="flex" justify="space-around">
        <el-col :span="12" :offset="1">
          <span>
            <span style="color: red;">*</span> 司机：{{ form.drivers.length }}/{{ max }}
            <el-tooltip effect="dark" placement="top" content="提交订单后将为每位司机生成相同的订单">
              <i class="el-icon-question"></i>
            </el-tooltip>
          </span>
        </el-col>
        <el-col :span="2">
          <el-button type="success" plain @click="open = true">选择司机</el-button>
        </el-col>
        <el-col :span="8"></el-col>
      </el-row>
      <el-row>
        <el-col :span="14" :offset="1">
          <el-table :data="form.drivers">
            <el-table-column label="姓名" align="center" prop="driverName" />
            <el-table-column label="手机号" align="center" prop="telephone" width="115" />
            <el-table-column label="准驾车型" align="center" prop="vehicleClass" />
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <el-button
                  style="color: red;"
                  size="mini"
                  type="text"
                  @click="removeDriver(scope.row)"
                >移除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
        <el-col :span="8"></el-col>
      </el-row>

    </el-form>

    <div class="footer-but">
      <el-button type="primary" :disabled="disabled" @click="submitForm">提 交</el-button>
      <el-button @click="close">关 闭</el-button>
    </div>

    <!-- 地图 -->
    <el-dialog title="选择装货地址" :visible.sync="openMapF" width="1500px" append-to-body :close-on-click-modal="false">
      <GDMapF mapId="mapF" @getAddress="getAddressF" />
    </el-dialog>

    <!-- 地图 -->
    <el-dialog title="选择收货地址" :visible.sync="openMapS" width="1500px" append-to-body :close-on-click-modal="false">
      <GDMapS mapId="mapS" @getAddress="getAddressS" />
    </el-dialog>

    <!-- 常用地址 -->
    <el-dialog title="选择装货地址" :visible.sync="openOrderAddressF" width="1500px" append-to-body :close-on-click-modal="false">
      <OrderAddressF mode="2" active="1" @getOrderAddress="getOrderAddressF" />
    </el-dialog>

    <!-- 常用地址 -->
    <el-dialog title="选择收货地址" :visible.sync="openOrderAddressS" width="1500px" append-to-body :close-on-click-modal="false">
      <OrderAddressS mode="2" :active="active" @getOrderAddress="getOrderAddressS" />
    </el-dialog>

    <!-- 选择司机对话框 -->
    <el-dialog title="选择司机" :visible.sync="open" width="1500px" append-to-body :close-on-click-modal="false">
      <driver-select :list="form.drivers" @driverSelect="driverSelect" />
    </el-dialog>

  </div>
</template>

<script>
import { addOrder } from "@/api/tws/order";
import GDMapF from '@/components/Map/GDMap';
import GDMapS from '@/components/Map/GDMap';
import OrderAddressF from '@/components/OrderAddress/index';
import OrderAddressS from '@/components/OrderAddress/index';
import DriverSelect from '@/components/DriverSelect/index';

export default {
  components: {
    GDMapF,
    GDMapS,
    OrderAddressF,
    OrderAddressS,
    DriverSelect
  },
  data() {
    var checkAmount = (rule, value, callback) => {
      if (!value || value <= 0) {
        return callback(new Error('运费金额不能为0'));
      } else {
        callback();
      }
    };
    var checkWeight = (rule, value, callback) => {
      if (!value || value <= 0) {
        return callback(new Error('货物毛重不能为0'));
      } else {
        callback();
      }
    };
    return {
      // 禁用确定按钮
      disabled: false,
      open: false,
      openOrderAddressF: false,
      openOrderAddressS: false,
      openMapF: false,
      openMapS: false,
      active: '2',
      // 最多可选司机数量
      max: 10,
      // 货物类型字典数据
      cargoTypeClassificationOptions: [],
      // 货物毛重校验
      weightRules: checkWeight,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        consignor: [
          { required: true, message: "发货方名称不能为空", trigger: ["blur", "change"] }
        ],
        consignorId: [
          { required: true, message: "发货方统一社会信用代码或个人证件号不能为空", trigger: ["blur", "change"] }
        ],
        placeOfLoading: [
          { required: true, message: "装货地址不能为空", trigger: ["blur", "change"] }
        ],
        consignee: [
          { required: true, message: "收货方名称不能为空", trigger: ["blur", "change"] }
        ],
        goodsReceiptPlace: [
          { required: true, message: "收货地址不能为空", trigger: ["blur", "change"] }
        ],
        totalMonetaryAmount: [
          { required: true, validator: checkAmount, trigger: ["blur", "change"] }
        ],
      }
    };
  },
  created() {
    this.reset();
    this.getDict();
  },
  methods: {
    /** 查询字典 */
    getDict() {
      // 货物类型字典
      this.getDicts("cargo_type_classification").then(response => {
        this.cargoTypeClassificationOptions = response.data;
      });
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        originalDocumentNumber: null,
        shippingNoteNumber: null,
        serialNumber: null,
        vehicleAmount: null,
        transportTypeCode: null,
        businessTypeCode: null,
        totalMonetaryAmount: null,
        policyNumber: null,
        insuranceCompanyCode: null,
        leaveTime: null,
        carNeed: null,
        remark: null,
        consignor: null,
        consignorId: null,
        loadLinkTel: null,
        placeOfLoading: null,
        countrySubdivisionCode: null,
        startLongitude: null,
        startLatitude: null,
        consignee: null,
        consigneeId: null,
        receiptLinkTel: null,
        goodsReceiptPlace: null,
        countrySubdivisionCodeS: null,
        endLongitude: null,
        endLatitude: null,
        actualCarrierName: null,
        actualCarrierBusinessLicense: null,
        actualCarrierId: null,
        driverId: null,
        driverLicense: null,
        driverName: null,
        driverPhone: null,
        vehicleId: null,
        vehicleNumber: null,
        vehiclePlateColorCode: null,
        trailerVehicleId: null,
        trailerVehiclePlateNumber: null,
        trailerVehiclePlateColorCode: null,
        despatchActualDateTime: null,
        goodsReceiptDateTime: null,
        isReceipt: null,
        backImages: null,
        starCompany: null,
        starDriver: null,
        status: null,
        isPay: null,
        isBill: null,
        isSendToPro: null,
        sendToProDateTime: null,
        tenantId: null,
        companyName: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        delFlag: null,
        orderGoods: [],
        drivers: []
      };
      this.resetForm("form");
      this.addDomain();
    },
    // 选择装货地的回调
    getAddressF(adcode, address, lng, lat) {
      this.openMapF = false;
      this.form.countrySubdivisionCode = adcode;
      this.form.placeOfLoading = address;
      this.form.startLongitude = lng;
      this.form.startLatitude = lat;
    },
    // 选择收货地的回调
    getAddressS(adcode, address, lng, lat) {
      this.openMapS = false;
      this.form.countrySubdivisionCodeS = adcode;
      this.form.goodsReceiptPlace = address;
      this.form.endLongitude = lng;
      this.form.endLatitude = lat;
    },
    openOrderAddressSFuc() {
      this.openOrderAddressS = true;
      this.active = '1';
      setTimeout(() => {
        this.active = '2';
      })
    },
    // 选择常用装货地的回调
    getOrderAddressF(or) {
      this.openOrderAddressF = false;
      this.form.countrySubdivisionCode = or.cityCode;
      this.form.placeOfLoading = or.address;
      this.form.startLongitude = or.longitude;
      this.form.startLatitude = or.latitude;
      this.form.consignor = or.name;
      this.form.consignorId = or.idCard;
      this.form.loadLinkTel = or.linkTel;
    },
    // 选择常用收货地的回调
    getOrderAddressS(or) {
      this.openOrderAddressS = false;
      this.form.countrySubdivisionCodeS = or.cityCode;
      this.form.goodsReceiptPlace = or.address;
      this.form.endLongitude = or.longitude;
      this.form.endLatitude = or.latitude;
      this.form.consignee = or.name;
      this.form.consigneeId = or.idCard;
      this.form.receiptLinkTel = or.linkTel;
    },
    // 添加一行货物
    addDomain() {
      this.form.orderGoods.push({
        descriptionOfGoods: '',
        cargoTypeClassificationCode: '',
        goodsItemGrossWeight: 0
      });
    },
    // 删除一行货物
    removeDomain(item) {
      var index = this.form.orderGoods.indexOf(item);
      if (index !== -1) {
        this.form.orderGoods.splice(index, 1);
      }
    },
    // 选择司机的回调
    driverSelect(drivers) {
      this.open = false;
      this.form.drivers = drivers;
    },
    // 移除司机
    removeDriver(driver) {
      var index = this.form.drivers.indexOf(driver);
      if (index !== -1) {
        this.form.drivers.splice(index, 1);
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.disabled = true;
      this.$refs["form"].validate(valid => {
        if (valid) {
          if(!this.form.orderGoods || this.form.orderGoods.length == 0) {
            this.$modal.msgError("请添加货物");
            return
          }
          if(!this.form.drivers || this.form.drivers.length == 0) {
            this.$modal.msgError("请选择司机");
            return
          }
          addOrder(this.form).then(response => {
            this.$modal.msgSuccess("订单已提交");
            this.disabled = false;
            this.reset();
          }).catch(err => {
            this.disabled = false;
          })
        } else {
          this.disabled = false;
        }
      });
    },
    // 关闭按钮
    close() {
      this.$tab.closePage();
    }
  }
};
</script>

<style>
  .divider_color {
    color: #409eff;
  }
  .o_input {
    width: 170%;
  }
  .o_select {
    width: 121%;
  }
  .footer-but {
    text-align: center;
    margin: 20px 0;
  }
</style>
